<?php

/*
=====================================================
 FluxBB - Delux Board Converstations (DBC)
-----------------------------------------------------
 http://dbc-forum.com/
 http://fluxbb.org/
-----------------------------------------------------
 Copyright (c) 2010,2011 FluxBB - Delux Board Conversations (DBC)
-----------------------------------------------------
 Предсловие: Данный скрипт (DBC) не является работой с нуля, то 
 есть ядром скрипта всё также остаётся FuxBB,но теперь в оболочке
 DBC.
=====================================================
*/

if (isset($_GET['action']))
	define('DBC_QUIET_VISIT', 1);

define('DBC_ROOT', './');
define('DBC_TURN_OFF_MAINT', 1);
require DBC_ROOT.'engine/common.php';
// Load the login.php language file
require DBC_ROOT.'language/'.$DBC_user['language'].'/login.php';

$action = isset($_GET['action']) ? $_GET['action'] : null;

if ($DBC_config['o_blocking_time'] != '0' && $action != 'out')
{
	$block_time_term = time() - 60 * $DBC_config['o_blocking_time'];
	$db->query('DELETE FROM '.$db->prefix.'blocking WHERE block_log < '.$block_time_term) or error('Unable to delete from blocking list', __FILE__, __LINE__, $db->error());
	$block_q = ($DBC_config['o_blocking_reglog'] == '1') ? '(block_type=1 OR block_type=2)' : 'block_type=2';
	$result = $db->query('SELECT block_ip FROM '.$db->prefix.'blocking WHERE block_ip=\''.$db->escape(get_remote_address()).'\' AND '.$block_q) or error('Unable to fetch blocking info', __FILE__, __LINE__, $db->error());
	$block_kolvo = $db->num_rows($result);
	if ($block_kolvo > $DBC_config['o_blocking_kolvo'])
		message($lang_common['Limit of errors']);
}

if (isset($_POST['form_sent']) && $action == 'in')
{
	$form_username = DBC_trim($_POST['req_username']);
	$form_password = DBC_trim($_POST['req_password']);
	$save_pass = isset($_POST['save_pass']);

	$username_sql = ($db_type == 'mysql' || $db_type == 'mysqli' || $db_type == 'mysql_innodb' || $db_type == 'mysqli_innodb') ? 'username=\''.$db->escape($form_username).'\'' : 'LOWER(username)=LOWER(\''.$db->escape($form_username).'\')';

	if ($DBC_config['o_check_ip'] == '1')
		$result = $db->query('SELECT u.*, g.g_id, g.g_moderator FROM '.$db->prefix.'users AS u LEFT JOIN '.$db->prefix.'groups AS g ON u.group_id=g.g_id WHERE '.$username_sql) or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
	else
		$result = $db->query('SELECT * FROM '.$db->prefix.'users WHERE '.$username_sql) or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
	$cur_user = $db->fetch_assoc($result);

	$authorized = false;

	if (!empty($cur_user['password']))
	{
		$form_password_hash = DBC_hash($form_password); // Will result in a SHA-1 hash

		// If there is a salt in the database we have upgraded from 1.3-legacy though havent yet logged in
		if (!empty($cur_user['salt']))
		{
			if (sha1($cur_user['salt'].sha1($form_password)) == $cur_user['password']) // 1.3 used sha1(salt.sha1(pass))
			{
				$authorized = true;

				$db->query('UPDATE '.$db->prefix.'users SET password=\''.$form_password_hash.'\', salt=NULL WHERE id='.$cur_user['id']) or error('Unable to update user password', __FILE__, __LINE__, $db->error());
			}
		}
		// If the length isn't 40 then the password isn't using sha1, so it must be md5 from 1.2
		else if (strlen($cur_user['password']) != 40)
		{
			if (md5($form_password) == $cur_user['password'])
			{
				$authorized = true;

				$db->query('UPDATE '.$db->prefix.'users SET password=\''.$form_password_hash.'\' WHERE id='.$cur_user['id']) or error('Unable to update user password', __FILE__, __LINE__, $db->error());
			}
		}
		// Otherwise we should have a normal sha1 password
		else
			$authorized = ($cur_user['password'] == $form_password_hash);
	}

	if (!$authorized != '1')
	{
		if ($DBC_config['o_blocking_time'] != '0')
		{
			$db->query('INSERT INTO '.$db->prefix.'blocking (block_ip, block_log, block_type) VALUES(\''.$db->escape(get_remote_address()).'\', '.time().', 2)') or error('Unable to create blocking', __FILE__, __LINE__, $db->error());

			$block_kolvo = $block_kolvo + 1;
			if ($block_kolvo > $DBC_config['o_blocking_kolvo'] && ($DBC_config['o_blocking_user'] != '1' || ($DBC_config['o_blocking_user'] == '1' && !empty($cur_user['password']))))
			{
				$reason = '[MOD] Auto Bloking. Error input login.php'."\n\n".'IP = '.get_remote_address()."\n".'UserName = '.$form_username."\n";
				// Should we use the internal report handling?
				if ($DBC_config['o_report_method'] == '0' || $DBC_config['o_report_method'] == '2')
					$db->query('INSERT INTO '.$db->prefix.'reports (post_id, topic_id, forum_id, reported_by, created, message) VALUES(0, 0, 0, '.$DBC_user['id'].', '.time().', \''.$db->escape($reason).'\')' ) or error('Unable to create report', __FILE__, __LINE__, $db->error());

				message($lang_common['Limit of errors']);
			}
		}
	}

	if (!$authorized)
		message($lang_login['Wrong user/pass'].' <a href="login.php?action=forget">'.$lang_login['Forgotten pass'].'</a>');

	// Update the status if this is the first time the user logged in
	if ($cur_user['group_id'] == DBC_UNVERIFIED)
	{
		$db->query('UPDATE '.$db->prefix.'users SET group_id='.$DBC_config['o_default_user_group'].' WHERE id='.$cur_user['id']) or error('Unable to update user status', __FILE__, __LINE__, $db->error());

		// Regenerate the users info cache
		if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
			require DBC_ROOT.'engine/cache.php';

		generate_users_info_cache();
	}


  if ($DBC_config['o_check_ip'] == '1')
    if ($cur_user['g_id'] == DBC_ADMIN || $cur_user['g_moderator'] == '1')
      $db->query('UPDATE '.$db->prefix.'users SET registration_ip=\''.$db->escape(get_remote_address()).'\' WHERE id='.$cur_user['id']) or error('Unable to update user IP', __FILE__, __LINE__, $db->error());
    
	// Remove this users guest entry from the online list
	$db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape(get_remote_address()).'\'') or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());

	$expire = ($save_pass == '1') ? time() + 31536000 : time() + $DBC_config['o_timeout_visit'];
	DBC_setcookie($cur_user['id'], $form_password_hash, $expire);

	// Reset tracked topics
	set_tracked_topics(null);

	redirect(htmlspecialchars($_POST['redirect_url']), $lang_login['Login redirect']);
}


else if ($action == 'out')
{
	if ($DBC_user['is_guest'] || !isset($_GET['id']) || $_GET['id'] != $DBC_user['id'] || !isset($_GET['csrf_token']) || $_GET['csrf_token'] != DBC_hash($DBC_user['id'].DBC_hash(get_remote_address())))
	{
		header('Location: index.php');
		exit;
	}

	// Remove user from "users online" list
	$db->query('DELETE FROM '.$db->prefix.'online WHERE user_id='.$DBC_user['id']) or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());

	// Update last_visit (make sure there's something to update it with)
	if (isset($DBC_user['logged']))
		$db->query('UPDATE '.$db->prefix.'users SET last_visit='.$DBC_user['logged'].' WHERE id='.$DBC_user['id']) or error('Unable to update user visit data', __FILE__, __LINE__, $db->error());

	DBC_setcookie(1, md5(uniqid(rand(), true)), time() + 31536000);

	redirect('index.php', $lang_login['Logout redirect']);
}


else if ($action == 'forget' || $action == 'forget_2')
{
	if (!$DBC_user['is_guest'])
		header('Location: index.php');

	if (isset($_POST['form_sent']))
	{
		// Start with a clean slate
		$errors = array();

		require DBC_ROOT.'engine/email.php';

		// Validate the email address
		$email = strtolower(trim($_POST['req_email']));
		if (!is_valid_email($email))
			$errors[] = $lang_common['Invalid email'];

		// Did everything go according to plan?
		if (empty($errors))
		{
			$result = $db->query('SELECT id, username, last_email_sent FROM '.$db->prefix.'users WHERE email=\''.$db->escape($email).'\'') or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());

			if ($db->num_rows($result))
			{
				// Load the "activate password" template
				$mail_tpl = trim(file_get_contents(DBC_ROOT.'language/'.$DBC_user['language'].'/mail_templates/activate_password.tpl'));

				// The first row contains the subject
				$first_crlf = strpos($mail_tpl, "\n");
				$mail_subject = trim(substr($mail_tpl, 8, $first_crlf-8));
				$mail_message = trim(substr($mail_tpl, $first_crlf));

				// Do the generic replacements first (they apply to all emails sent out here)
				$mail_message = str_replace('<base_url>', $DBC_config['o_base_url'].'/', $mail_message);
				$mail_message = str_replace('<board_mailer>', $DBC_config['o_board_title'].' '.$lang_common['Mailer'], $mail_message);

				// Loop through users we found
				while ($cur_hit = $db->fetch_assoc($result))
				{
					if ($cur_hit['last_email_sent'] != '' && (time() - $cur_hit['last_email_sent']) < 3600 && (time() - $cur_hit['last_email_sent']) >= 0)
						message($lang_login['Email flood'], true);

					// Generate a new password and a new password activation code
					$new_password = random_pass(10);
					$new_password_key = random_pass(8);

					$db->query('UPDATE '.$db->prefix.'users SET activate_string=\''.DBC_hash($new_password).'\', activate_key=\''.$new_password_key.'\', last_email_sent = '.time().' WHERE id='.$cur_hit['id']) or error('Unable to update activation data', __FILE__, __LINE__, $db->error());

					// Do the user specific replacements to the template
					$cur_mail_message = str_replace('<username>', $cur_hit['username'], $mail_message);
					$cur_mail_message = str_replace('<activation_url>', $DBC_config['o_base_url'].'/profile.php?id='.$cur_hit['id'].'&action=change_pass&key='.$new_password_key, $cur_mail_message);
					$cur_mail_message = str_replace('<new_password>', $new_password, $cur_mail_message);

					DBC_mail($email, $mail_subject, $cur_mail_message);
				}

				message($lang_login['Forget mail'].' <a href="mailto:'.$DBC_config['o_admin_email'].'">'.$DBC_config['o_admin_email'].'</a>.', true);
			}
			else
				$errors[] = $lang_login['No email match'].' '.htmlspecialchars($email).'.';
			}
		}

	$page_title = array(DBC_htmlspecialchars($DBC_config['o_board_title']), $lang_login['Request pass']);
	$required_fields = array('req_email' => $lang_common['Email']);
	$focus_element = array('request_pass', 'req_email');
	define ('DBC_ACTIVE_PAGE', 'login');
	define('DBC_LOST_PASSWORD', 1);
	require DBC_ROOT.'engine/engine.php';

// If there are errors, we display them
if (!empty($errors))
{
	if ($DBC_config['o_blocking_time'] != '0')
	{
		$db->query('INSERT INTO '.$db->prefix.'blocking (block_ip, block_log, block_type) VALUES(\''.$db->escape(get_remote_address()).'\', '.time().', 2)') or error('Unable to create blocking', __FILE__, __LINE__, $db->error());

		$block_kolvo = $block_kolvo + 1;
		if ($block_kolvo > $DBC_config['o_blocking_kolvo'])
		{
			$reason = '[MOD] Auto Bloking. Error input login.php'."\n\n".'IP = '.get_remote_address()."\n".'UserName = ---'."\n".'Email = '.$email."\n";
			// Should we use the internal report handling?
			if ($DBC_config['o_report_method'] == '0' || $DBC_config['o_report_method'] == '2')
				$db->query('INSERT INTO '.$db->prefix.'reports (post_id, topic_id, forum_id, reported_by, created, message) VALUES(0, 0, 0, '.$DBC_user['id'].', '.time().', \''.$db->escape($reason).'\')' ) or error('Unable to create report', __FILE__, __LINE__, $db->error());

			message($lang_common['Limit of errors']);
		}
	}

?>
<div id="posterror" class="block">
	<h2><span><?php echo $lang_login['New password errors'] ?></span></h2>
	<div class="box">
		<div class="inbox error-info">
			<p><?php echo $lang_login['New passworderrors info'] ?></p>
			<ul class="error-list">
<?php

	foreach ($errors as $cur_error)
		echo "\t\t\t\t".'<li><strong>'.$cur_error.'</strong></li>'."\n";
?>
			</ul>
		</div>
	</div>
</div>

<?php

}
?>

<table width="100%" height="38" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="28" class="bg_forum_title_left"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_title_center"><span class="cat_title"><?php echo $lang_common['Login'] ?></span></td>
<td align="center" width="28" class="bg_forum_title_right"><img src="engine/skins/images/spacer.gif" border="0"></td>
</tr></table>


		<form id="request_pass" method="post" action="login.php?action=forget_2" onsubmit="this.request_pass.disabled=true;if(process_form(this)){return true;}else{this.request_pass.disabled=false;return false;}">
					<div class="login_info"><?php echo $lang_login['Request pass legend'] ?></div><div class="login_detals">

						<input type="hidden" name="form_sent" value="1" />
						<label class="required"><strong><?php echo $lang_common['Email'] ?> <span><?php echo $lang_common['Required'] ?></span></strong><br /><input id="req_email" class="input_text" type="text" name="req_email" size="50" maxlength="80" /><br /></label>
						<br/><div class="infoblock"><div class="infoblock_p"><p class="actions"><span><?php echo $lang_login['Request pass info'] ?></span></p></div></div><br/>
			<p class="buttons"><input type="submit" class="fbutton" name="request_pass" value="<?php echo $lang_common['Submit'] ?>" /><?php if (empty($errors)): ?> <a href="javascript:history.go(-1)"><?php echo $lang_common['Go back'] ?></a><?php endif; ?></p>
	</div></form>




<table width="100%" height="23" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="30" class="bg_forum_bott_left"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_bott_center"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="center" width="30" class="bg_forum_bott_right"><img src="engine/skins/images/spacer.gif" border="0"></td>
</tr></thead></table>

<?php
	$footer_style = 'index';
	require DBC_ROOT.'engine/footer.php';
}


if (!$DBC_user['is_guest'])
	header('Location: index.php');

// Try to determine if the data in HTTP_REFERER is valid (if not, we redirect to index.php after login)
$redirect_url = (isset($_SERVER['HTTP_REFERER']) && preg_match('#^'.preg_quote($DBC_config['o_base_url']).'/(.*?)\.php#i', $_SERVER['HTTP_REFERER'])) ? htmlspecialchars($_SERVER['HTTP_REFERER']) : $DBC_config['o_base_url'].'/index.php';

if ($DBC_config['o_coding_forms'] == '1')
	$page_head['decode64'] = '';

$page_title = array(DBC_htmlspecialchars($DBC_config['o_board_title']), $lang_common['Login']);
$required_fields = array('req_username' => $lang_common['Username'], 'req_password' => $lang_common['Password']);
$focus_element = array('login', 'req_username');
define('DBC_ACTIVE_PAGE', 'login');
define('DBC_LOGIN', 1);
require DBC_ROOT.'engine/engine.php';

?>

	<table width="100%" height="38" border="0" cellpadding="0" cellspacing="0"><thead><tr>
	<td align="left" width="28" class="bg_forum_title_left"><img src="engine/skins/images/spacer.gif" border="0"></td>
	<td align="left" class="bg_forum_title_center"><span class="cat_title"><?php echo $lang_common['Login'] ?></span></td>
	<td align="center" width="28" class="bg_forum_title_right"><img src="engine/skins/images/spacer.gif" border="0"></td>
	</tr></table>
	
	<table class="forum_adv_table"  width="100%" border="0" cellpadding="0" cellspacing="0"><thead><tr>
	<td align="left" class="forum_adv_tleft" width="2"><img src="engine/skins/images/spacer.gif" border="0"></td>
	<td align="left" width="100%"><div class="forum_adv">

		<form id="login" method="post" action="login.php?action=in" onsubmit="return process_form(this)">
					<div class="login_info"><?php echo $lang_login['Login legend'] ?></div><div class="login_detals">
						<input type="hidden" name="form_sent" value="1" />
						<input type="hidden" name="csrf_tokn" value="<?php echo DBC_hash('2'.DBC_hash(get_remote_address())) ?>" />
						<input type="hidden" name="redirect_url" value="<?php echo $redirect_url ?>" />
						<label class="conl required"><strong><?php echo $lang_common['Username'] ?> <span><?php echo $lang_common['Required'] ?></span></strong><br /><input type="text" name="req_username" size="25" maxlength="25" tabindex="1" class="input_text" /><br /></label>
						<label class="conl required"><strong><?php echo $lang_common['Password'] ?> <span><?php echo $lang_common['Required'] ?></span></strong><br /><input type="password" name="req_password" size="25" tabindex="2" class="input_text" /><br /></label>
<br /><br />
							<label><input type="checkbox" class="input_check" name="save_pass" value="1" tabindex="3" /><?php echo $lang_login['Remember me'] ?><br /></label>

						<p class="clearb"><?php echo $lang_login['Login info'] ?></p>
<div class="infoblock"><div class="infoblock_p">
						<p class="actions"><span><a href="register" tabindex="5"><?php echo $lang_login['Not registered'] ?></a></span> <span><a href="login.php?action=forget" tabindex="6"><?php echo $lang_login['Forgotten pass'] ?></a></span></p>
</div></div>
			<p class="buttons"><input type="submit" class="fbutton" name="login" value="<?php echo $lang_common['Login'] ?>" tabindex="3" /></p>
		</div></form>

<?php
$footer_style = 'index';
require DBC_ROOT.'engine/footer.php';